import HTTP from './http';
import StorageHelper from './storageHelper';
import { STORAGE_CONSTANT } from '../config/storage';
import { API, API_GENERATE } from '../config/api';


class ConstData {
  constructor() {
    this.duration = 2; // 过期时间区间(常量)->单位毫秒
    this.data = {};
  }

  async init() {
    this.data = await StorageHelper.get(STORAGE_CONSTANT.CONST_INFO) || {};
    this.data = JSON.parse(this.data)

    if (Object.keys(this.data).length == 0 || this.isExpired()) {
      this.getConstData();
    } else {
      await StorageHelper.set(STORAGE_CONSTANT.CONST_INFO, this.data);
      await StorageHelper.set(STORAGE_CONSTANT.CONST_INFO_EXPIRE, new Date().getTime() + this.duration);
    }
  }

  async getConstData() {
    this.data = await HTTP.POST(API_GENERATE(API.CONST)) || {};
    await StorageHelper.set(STORAGE_CONSTANT.CONST_INFO, this.data);
    await StorageHelper.set(STORAGE_CONSTANT.CONST_INFO_EXPIRE, new Date().getTime() + this.duration);
    return this.data;
  }

  async isExpired() {
    return new Date().getTime() >= await StorageHelper.get(STORAGE_CONSTANT.CONST_INFO_EXPIRE)
  }

  async get() {
    if (await this.isExpired()) { //过期
      return await this.getConstData();
    } else {
      let result = await StorageHelper.get(STORAGE_CONSTANT.CONST_INFO) || '{}';
      return JSON.parse(result);
    }
  }
}

module.exports = new ConstData();